package com.opages.mvc.adapter.consul.serviceregistry;

import com.ecwid.consul.ConsulException;
import com.ecwid.consul.v1.ConsulClient;
import com.opages.mvc.adapter.common.client.serviceregistry.ServiceRegistry;
import com.opages.mvc.adapter.consul.model.ConsulDiscoveryProperties;
import com.opages.mvc.adapter.consul.model.ClusterConsulClient;

/**
 * consul注册<动词语义>
 * @author daizhong.liu
 *
 */
public class ConsulServiceRegistry implements ServiceRegistry<ConsulRegistration>  {
    private ClusterConsulClient clusterConsulClient;
    private final ConsulDiscoveryProperties properties;
    private TtlScheduler ttlScheduler;
    public static final Long defaultInterval = 10000L;
    public ConsulServiceRegistry(ConsulDiscoveryProperties properties,ClusterConsulClient clusterConsulClient) {
        this.properties = properties;
        this.clusterConsulClient = clusterConsulClient;
        ttlScheduler = new TtlScheduler(clusterConsulClient,computeHearbeatInterval(properties.getTtl()));
    }

    @Override
    public void register(ConsulRegistration registration) {
        try {
            for(ConsulClient client : clusterConsulClient.getClients()) {
                client.agentServiceRegister(registration.getService(),this.properties.getAclToken());
            }
            ttlScheduler.add(registration.getService().getId());
        }
        catch (ConsulException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void deregister(ConsulRegistration registration) {
        for(ConsulClient client : clusterConsulClient.getClients()) {
            client.agentServiceDeregister(registration.getInstanceId(),this.properties.getAclToken());
        }
        ttlScheduler.remove(registration.getService().getId());
    }
    /**
     * 根据传给consul的心跳时间长,计算出小于心跳时间的定时任务周期时间
     * @Author daizhong.liu
     * @Param ttl consul判断客户端失效时间
     * @return 定时任务时间,时间为毫秒
     **/
    public long computeHearbeatInterval(String ttl) {
        Double intervalRatio = 2.0 / 3.0;
        Double schedulerTtl = convertLong(ttl) * intervalRatio;
        return schedulerTtl.longValue();
    }
    private long convertLong(String ttl) {
        try {
            if (ttl.endsWith("s")) {
                String second = ttl.replaceAll(ttl, "s");
                return Long.parseLong(second) * 1000;
            } else if (ttl.endsWith("m")) {
                String second = ttl.replaceAll(ttl, "m");
                return Long.parseLong(second) * 1000 * 60;
            } else if (ttl.endsWith("h")) {
                String second = ttl.replaceAll(ttl, "h");
                return Long.parseLong(second) * 1000 * 60 * 60;
            }
        }finally{
            return defaultInterval;
        }
    }
}
